﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TireService.Data;
using DevExpress.Web.ASPxCallback;
using System.Web.Security;

namespace TireService.Web.UserControls
{
    public partial class ucDeactivateSubscription : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }


        protected void callbackDeactivateCustomerSubscriptionPanel_Callback(object source, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
        {
            LoadUserControl(Convert.ToInt32(e.Parameter));
        }

        /// <summary>
        /// Public function for loading usercontrol
        /// </summary>
        public void LoadUserControl(int CustomerSubscriptionId)
        {
            // Show usercontrol edit form
            pDeactivateCustomerSubscription.Visible = true;

            // Initiate datalayer
            TireServiceDB db = new TireServiceDB();

            if (CustomerSubscriptionId != 0)
            {
                LoadCustomerSubscription(CustomerSubscriptionId, db);
            }
            else
            {
                // Error
                throw new ArgumentException("Abonnement blev ikke fundet");
            }
        }

        /// <summary>
        /// Function that load customersubscription
        /// </summary>
        /// <param name="CustomerSubscriptionId">Id on customer subscription</param>
        /// <param name="db">Connection to database</param>
        private void LoadCustomerSubscription(int CustomerSubscriptionId, TireServiceDB db)
        {
            // Fetch CustomerSubscription
            CustomerSubscription customersubscription = db.GetCustomerSubscription(CustomerSubscriptionId);

            // Set values in deactivation form
            if (customersubscription != null)
            {
                Customer customer = db.GetCustomer(customersubscription.CustomerId);
                List<Car> cars = db.GetCarByCustomerSubscriptionId(customersubscription.CustomerSubscriptionId);

                if (cars.Count == 0)
                {
                    throw new ArgumentException("Ingen bil er tilknyttet abonnement - kontakt systemadministration.");
                }
                if (cars.Count > 1)
                {
                    throw new ArgumentException("Mere end en bil er tilknyttet dette abonnement - kontakt systemadministration ifht. deaktivering af abonnement.");
                }

                lblCustomerIdValue.Text = customer.CustomerId.ToString();
                lblCustomerNameValue.Text = customer.Name;
                lblSubscriptionDescriptionValue.Text = db.GetSubscriptionDescription(customersubscription.SubscriptionId);
                lblCustomerSubscriptionIdValue.Text = customersubscription.CustomerId.ToString() + "-" + customersubscription.SubscriptionId.ToString() + "-" + customersubscription.CustomerSubscriptionId.ToString();
                lblCarRegistrationNumberValue.Text = cars.First().RegistrationNumber;

                // Show possible adresses to select from if tireset should be returned
                ddlReturnCustomerTireSetSelectAddress.Items.Clear();
                string add1 = customer.Address + "|" + customer.ZipCode + "|" + customer.City;
                string add2 = customer.SecondaryAddress + "|" + customer.SecondaryZipCode + "|" + customer.SecondaryCity;
                string add3 = "-- Anden adresse --";
                ddlReturnCustomerTireSetSelectAddress.Items.Add(add1, 0);
                ddlReturnCustomerTireSetSelectAddress.Items.Add(add2, 1);
                ddlReturnCustomerTireSetSelectAddress.Items.Add(add3, 2);
            }
            else
            {
                // Error
                throw new ArgumentException("Abonnement blev ikke fundet");
            }
        }

        /// <summary>
        /// Callback function that deactivates customersubscription and car
        /// </summary>
        protected void callBackDeactivateCustomerSubscription_Callback(object sender, CallbackEventArgs e)
        {
            try
            {
                // Get values from client (0: CustomerSubscriptionId, 1: Deactivationdate, 2: TireSetAction, 3: EmailConfirmation, 4: InvoiceCustomer (optional), 5: InvoicePrice (optional), 6: Address (optional), 7: ZipCode (optional), 8: City (optional), 9: Remark to address (optional), 10: Note to employee (optional))
                string[] param = e.Parameter.Split('|');

                int CustomerSubscriptionId = Convert.ToInt32(param[0]);

                // Get UserId (for logging)
                Guid UserId = new Guid(Membership.GetUser().ProviderUserKey.ToString());

                // Initiate datalayer
                TireServiceDB db = new TireServiceDB();

                // Get customer subscription
                CustomerSubscription customersubscription = db.GetCustomerSubscription(CustomerSubscriptionId);

                // TODO: Forhold til hvad der skal ske hvis der er åbne opgaver på bilen (ex. kun nogle bestemte typer - hjulskift)
                // TODO: Check tidligt at udleveringsadressen ikke ligger udenfor lager rækkevidde

                // Deactivate subscription
                customersubscription.InActive = true;
                customersubscription.InActiveDate = Convert.ToDateTime(param[1]);

                // Initiate customersubscription log
                CustomerSubscriptionLogBLL customersubscriptionlogBLL = new CustomerSubscriptionLogBLL();

                // Get car
                List<Car> cars = db.GetCarByCustomerSubscriptionId(customersubscription.CustomerSubscriptionId);
                if (cars.Count == 0)
                {
                    throw new ArgumentException("Ingen bil er tilknyttet abonnement - kontakt systemadministration.");
                }
                if (cars.Count > 1)
                {
                    throw new ArgumentException("Mere end en bil er tilknyttet dette abonnement - kontakt systemadministration ifht. deaktivering af abonnement.");
                }

                // Deactivate car
                Car car = cars.First();
                car.CarStatusId = (int)Shared.CarStatus.InActive;

                int TireSetAction = Convert.ToInt32(param[2]); // 1: Deliver tires to customer selected address, 2: Return from warehouse, 3: Tireset already returned, 4: Keep tireset

                // Instantiate task business logic layer
                TaskBLL taskBLL = new TaskBLL();

                // Declare invoice variable if invoicing is needed
                string invoiceid = string.Empty;

                // Declare string as input for message on tireset action
                string tiresetaction = "";

                // Get paying customer for invoicing and emailing confirmation
                CustomerBLL customerBLL = new CustomerBLL();
                int PayingCustomerId = customerBLL.GetPayingCustomerId(db, customersubscription.CustomerId);
                Customer payingcustomer = db.GetCustomer(PayingCustomerId);

                // Initiate E-conomic interface
                EconomicInterface ecoInterface = new EconomicInterface();

                if (TireSetAction == 1)
                {
                    // Deliver the tireset back to the customer

                    // Get tiresets on stock
                    int[] tiresetstatus = new int[] { (int)Shared.TireSetStatus.OnStock };
                    List<TireSet> tiresets = db.GetCarTireSetByTireSetStatus(car.CarId, tiresetstatus);

                    if (tiresets.Count == 0 | tiresets.Count > 1)
                    {
                        throw new ArgumentException("Hjulsæt ikke opbevaret på lager for kunden - deaktivering og udlevering kan derfor ikke gennemføres.");
                    }

                    // Create servicedrive task
                    Task task = taskBLL.CreateTask(db,
                                                    null,
                                                    (int)Shared.TaskType.ServiceDrive,
                                                    (int)Shared.TaskDetailType.ServiceDrive_ReturnTire,
                                                    (int)Shared.TaskTypeStatus.ServiceDrive_Created,
                                                    customersubscription.CustomerId,
                                                    car.CarId,
                                                    tiresets.First().TireSetId,
                                                    Convert.ToString(param[6]),
                                                    Convert.ToString(param[7]),
                                                    Convert.ToString(param[8]),
                                                    0,
                                                    Convert.ToString(param[9]),
                                                    Convert.ToString(param[6]),
                                                    Convert.ToString(param[7]),
                                                    Convert.ToString(param[8]),
                                                    0,
                                                    Convert.ToString(param[9]),
                                                    Convert.ToString(param[10]),
                                                    1,
                                                    UserId,
                                                    true);

                    tiresetaction = "Hjulsæt til bil bliver leveret på adressen: " + Convert.ToString(param[6]) + ", " + Convert.ToString(param[7]) + " " + Convert.ToString(param[8]) + " indenfor 12 arbejdsdage";

                    // Create subscription log
                    customersubscriptionlogBLL.CreateCustomerSubscriptionLog(db, customersubscription, (int)Shared.SubscriptionLogAction.DeActivated, UserId, "Opsagt - levering af hjul hos kunden");

                    // Check if invoicing needed
                    if (Convert.ToBoolean(param[4]))
                    {
                        // Create invoice

                        // Create orderline for invoicing
                        List<EconomicInterface.EcoOrderLine> orderlines = new List<EconomicInterface.EcoOrderLine>();

                        EconomicInterface.EcoOrderLine orderline = new EconomicInterface.EcoOrderLine();
                        orderline.ProductNumber = 8; // TODO: Make more dynamic
                        orderline.Description = "Aflevering af hjul for bil: " + car.RegistrationNumber;
                        orderline.Quantity = 1;
                        orderline.UnitPrice = Convert.ToDecimal(param[5]);

                        orderlines.Add(orderline);

                        // Create invoice in e-conomic
                        invoiceid = ecoInterface.CreateInvoice(db, customersubscription.CustomerId, car, orderlines, (!payingcustomer.ManualInvoicing));
                        //invoiceid = ecoInterface.CreateInvoice(db, customersubscription.CustomerId, orderlines, true);


                        // Extend text info for customer email with invoice
                        tiresetaction += "<br><br>I email er vedlagt faktura for udkørsel af hjulsæt.";
                    }
                }

                if (TireSetAction == 2)
                {
                    // Customer will pick-up tires on stock

                    // Get tiresets on stock
                    int[] tiresetstatus = new int[] { (int)Shared.TireSetStatus.OnStock };
                    List<TireSet> tiresets = db.GetCarTireSetByTireSetStatus(car.CarId, tiresetstatus);

                    if (tiresets.Count == 0 | tiresets.Count > 1)
                    {
                        throw new ArgumentException("Hjulsæt ikke opbevaret på lager for kunden - deaktivering og udlevering til kunden på lager kan derfor ikke gennemføres.");
                    }

                    // Create stock task - handout of tires to customer from stock
                    Task task = taskBLL.CreateTask(db,
                                                    null,
                                                    (int)Shared.TaskType.StockTask,
                                                    (int)Shared.TaskDetailType.StockTask_HandoutTireSet,
                                                    (int)Shared.TaskTypeStatus.StockTask_Created,
                                                    customersubscription.CustomerId,
                                                    car.CarId,
                                                    tiresets.First().TireSetId,
                                                    null,
                                                    null,
                                                    null,
                                                    0,
                                                    null,
                                                    null,
                                                    null,
                                                    null,
                                                    0,
                                                    null,
                                                    "Udlevering af hjul til opsagt kunde",
                                                    4,
                                                    UserId,
                                                    true);

                    tiresetaction = "Hjulsæt kan afhentes på vores lager.";

                    // Create subscription log
                    customersubscriptionlogBLL.CreateCustomerSubscriptionLog(db, customersubscription, (int)Shared.SubscriptionLogAction.DeActivated, UserId, "Opsagt - kunde afhenter hjul på lager");
                }

                if (TireSetAction == 3)
                {
                    // Tireset already returned / at the customers location
                    int[] tiresetstatus = new int[] { (int)Shared.TireSetStatus.OnStock, (int)Shared.TireSetStatus.AwaitsMoveToStock, (int)Shared.TireSetStatus.PlacedAtCustomer, (int)Shared.TireSetStatus.StockedAtCustomer };
                    List<TireSet> tiresets = db.GetCarTireSetByTireSetStatus(car.CarId, tiresetstatus);

                    if (tiresets.Count == 0 | tiresets.Count > 1)
                    {
                        throw new ArgumentException("Hjulsæt ikke fundet - deaktivering kan ikke gennemføres - kontakt systemadministration.");
                    }

                    TireSet tireset = tiresets.First();

                    // Create log for tiresets
                    TireSetLogBLL tiresetlogBLL = new TireSetLogBLL();
                    tiresetlogBLL.CreateTireSetLog(db, tireset, DateTime.Now, tireset.TireSetStatusId, (int)Shared.TireSetStatus.ReturnedToCustomer, UserId, "Deaktivering af abonnement og bil", null, null, null, null, null);

                    // Change status on the tireset
                    tireset.TireSetStatusId = (int)Shared.TireSetStatus.ReturnedToCustomer;

                    tiresetaction = "Hjulsæt er leveret retur.";

                    // Create subscription log
                    customersubscriptionlogBLL.CreateCustomerSubscriptionLog(db, customersubscription, (int)Shared.SubscriptionLogAction.DeActivated, UserId, "Opsagt - kunde har fået hjulene retur");
                }

                if (TireSetAction == 4)
                {
                    // Customer do not want tires back

                    // Get tiresets on stock
                    int[] tiresetstatus = new int[] { (int)Shared.TireSetStatus.OnStock };
                    List<TireSet> tiresets = db.GetCarTireSetByTireSetStatus(car.CarId, tiresetstatus);

                    if (tiresets.Count == 0 | tiresets.Count > 1)
                    {
                        throw new ArgumentException("Hjulsæt ikke opbevaret på lager for kunden - deaktivering og udlevering til kunden på lager kan derfor ikke gennemføres.");
                    }

                    // Create stock task - discard of tireset due to customer do not want it
                    Task task = taskBLL.CreateTask(db,
                                                    null,
                                                    (int)Shared.TaskType.StockTask,
                                                    (int)Shared.TaskDetailType.StockTask_DiscardTireSet,
                                                    (int)Shared.TaskTypeStatus.StockTask_Created,
                                                    customersubscription.CustomerId,
                                                    car.CarId,
                                                    tiresets.First().TireSetId,
                                                    null,
                                                    null,
                                                    null,
                                                    0,
                                                    null,
                                                    null,
                                                    null,
                                                    null,
                                                    0,
                                                    null,
                                                    "Hjulsæt kunde ikke ønsker efter opsigelse",
                                                    4,
                                                    UserId,
                                                    true);

                    tiresetaction = "De har angivet de ikke ønsker de opbevarede hjulsæt længere.";

                    // Create subscription log
                    customersubscriptionlogBLL.CreateCustomerSubscriptionLog(db, customersubscription, (int)Shared.SubscriptionLogAction.DeActivated, UserId, "Opsagt - kunde ønsker ikke længere hjulene");
                }

                // Check if email confirmation should be send to customer
                if (Convert.ToBoolean(param[3]))
                {
                    // Send email to customer (paying customer is always the one who receives email notification
                    
                    // Initiate email service
                    EmailNotificationServices emailService = new EmailNotificationServices();

                    CustomerSubscriptionBLL customersubscriptionBLL = new CustomerSubscriptionBLL();

                    // Check if invoicing has happend
                    if (Convert.ToBoolean(param[4]))
                    {
                        emailService.SubscriptionDeactivation_SendCustomerNotification(payingcustomer.CustomerId, payingcustomer.Email, payingcustomer.Name, customersubscriptionBLL.GetSubscriptionNumber(customersubscription), car.RegistrationNumber, tiresetaction, invoiceid, ecoInterface.GetInvoice(Convert.ToInt32(invoiceid)), "Faktura" + invoiceid + ".pdf");
                    }
                    else
                    {
                        emailService.SubscriptionDeactivation_SendCustomerNotification(payingcustomer.CustomerId, payingcustomer.Email, payingcustomer.Name, customersubscriptionBLL.GetSubscriptionNumber(customersubscription), car.RegistrationNumber, tiresetaction);
                    }
                    
                }

                // Commit changes to database
                db.SubmitChanges();

                // Dispose database connection
                db.Dispose();
            }
            catch (Exception ex)
            {
                // Error
                throw new ArgumentException("Fejl opstod: " + ex.Message);
            }
        }

    }
}